/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.content;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.grayrabbit.cms.action.common.BaseAction;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.constant.ContentStatic;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.constant.ConstantEnum.Module;
import org.grayrabbit.cms.constant.ConstantEnum.OperAct;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Category;
import org.grayrabbit.cms.entity.Content;
import org.grayrabbit.cms.entity.ContentAttach;
import org.grayrabbit.cms.entity.Dictionary;
import org.grayrabbit.cms.entity.OperLog;
import org.grayrabbit.cms.entity.PictureContent;
import org.grayrabbit.cms.entity.Topic;
import org.grayrabbit.cms.service.category.CategoryService;
import org.grayrabbit.cms.service.content.ContentAttachService;
import org.grayrabbit.cms.service.content.ContentService;
import org.grayrabbit.cms.service.content.PictureContentService;
import org.grayrabbit.cms.service.dictionary.DictionaryService;
import org.grayrabbit.cms.service.system.ConfigService;
import org.grayrabbit.cms.service.system.OperLogService;
import org.grayrabbit.cms.service.topic.TopicService;
import org.grayrabbit.cms.util.IpUtil;
import org.grayrabbit.cms.vo.category.CategoryBean;
import org.grayrabbit.cms.vo.content.ContentAttachBean;
import org.grayrabbit.cms.vo.content.PictureContentBean;
import org.grayrabbit.cms.vo.system.OperLogBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import org.grayrabbit.dao.util.Page;

/**
 * <b>ContentAction</b> Struts2 action�?

 * @version 1.0,创建时间:2011-05-16 14:40:11 
 */
@Controller
@Scope("prototype")
@Results( {
		@Result(name = "input", type = "dispatcher", location = "picturecontent-input.jsp"),
		@Result(name = "success", type = "dispatcher", location = "picturecontent-list.jsp")	
		}
		)
public class PictureContentAction extends BaseAction<PictureContentBean> {
	private static final long serialVersionUID = -1L;
	//Service接口接入
	@Autowired
	@Qualifier("pictureContentServiceImpl")
	private PictureContentService pictureContentService;
	
	@Autowired
	@Qualifier("contentAttachServiceImpl")
	private ContentAttachService contentAttachService;
	
	@Autowired
	@Qualifier("categoryServiceImpl")
	private CategoryService categoryService;
	
	@Autowired
	@Qualifier("dictionaryServiceImpl")
	private DictionaryService dictionaryService;
	
	@Autowired
	@Qualifier("operLogServiceImpl")
	private OperLogService operLogService;
	
	@Autowired
	@Qualifier("topicServiceImpl")
	private TopicService topicService;
	
	@Autowired
	@Qualifier("configServiceImpl")
	private ConfigService configService;
	
	@Autowired
	@Qualifier("contentServiceImpl")
	private ContentService contentService;
	
	//VO对象，由前端页面数据组装
	private PictureContentBean pictureContent;
	private List<Dictionary> dicContentType;
	private List<Dictionary> dicIsTop;
	private List<Dictionary> dicAudit;
	private List<Dictionary> dicIsComment;
	private List<Dictionary> dicPublishType;
	private String contextType;
	private ContentAttachBean contentAttach;
	private String cflag;
	private OperLog operLog = new OperLog();
	private List<OperLog> operLogList;
	private Topic topic;
	private List<String> contenttpllist=new ArrayList<String>();
	private List<String> toptpllist=new ArrayList<String>();
	private List<String> checkRepeatList=new ArrayList<String>();
	private String status;
	
	public List<Dictionary> getDicPublishType() {
		return dicPublishType;
	}

	public void setDicPublishType(List<Dictionary> dicPublishType) {
		this.dicPublishType = dicPublishType;
	}
	
	public List<Dictionary> getDicIsComment() {
		return dicIsComment;
	}

	public void setDicIsComment(List<Dictionary> dicIsComment) {
		this.dicIsComment = dicIsComment;
	}

	public OperLog getOperLog() {
		return operLog;
	}

	public void setOperLog(OperLog operLog) {
		this.operLog = operLog;
	}

	public List<OperLog> getOperLogList() {
		return operLogList;
	}

	public void setOperLogList(List<OperLog> operLogList) {
		this.operLogList = operLogList;
	}

	public List<Dictionary> getDicAudit() {
		return dicAudit;
	}

	public void setDicAudit(List<Dictionary> dicAudit) {
		this.dicAudit = dicAudit;
	}

	public String getCflag() {
		return cflag;
	}

	public void setCflag(String cflag) {
		this.cflag = cflag;
	}

	
	public ContentAttachBean getContentAttach() {
		return contentAttach;
	}

	public void setContentAttach(ContentAttachBean contentAttach) {
		this.contentAttach = contentAttach;
	}

	public List<Dictionary> getDicIsTop() {
		return dicIsTop;
	}

	public void setDicIsTop(List<Dictionary> dicIsTop) {
		this.dicIsTop = dicIsTop;
	}

	public String getContextType() {
		return contextType;
	}

	public void setContextType(String contextType) {
		this.contextType = contextType;
	}

	public List<Dictionary> getDicContentType() {
		return dicContentType;
	}

	public void setDicContentType(List<Dictionary> dicContentType) {
		this.dicContentType = dicContentType;
	}

	/**return 前端页面数据组装VO对象,<b>ContentBean</b>*/
	public PictureContentBean getPictureContent() {
		return pictureContent;
	}

	public void setPictureContent(PictureContentBean pictureContent) {
		this.pictureContent = pictureContent;
	}
	
	//分页对象
	private Page<PictureContent> page = new Page<PictureContent>(MAX_PAGE_NUM,true);
	
	/*
	 * return分页对象，默认实例化。如：page.pageNu=2,将更新相应的对象property
	 */
	public Page<PictureContent> getPage() {
		return page;
	}
	//接收前端form,url提交参数组装成分页property
	public void setPage(Page<PictureContent> page) {
		this.page = page;
	}
	
	/**
	 * 在执行（struts2的action调用时）list()方法前执行本方法
	 */
	public void prepareList(){
		prepareModel();
	}
	
	/**
	 * 在执行任何其它action方法（struts2的action调用时）前执行本方法
	 */
	public void prepare(){
		if(pictureContent==null){
			pictureContent = new PictureContentBean();
		}
	}
	/**
	 * 实现ModelDriven的接口简例前端页的bean组装写法,
	 *  如：
	 *	<pre>
	 *		<code> name="user.userName"</code>
	 *	改写成：
	 *		<code> name="userName"</code>
	 *	action实例中，会自动组成user成员变量
	 *	</pre>
	 */
	public PictureContentBean getModel() {
		return pictureContent;
	}
	
	@Override
	protected void prepareModel(){
		if(pictureContent!=null&&StringUtils.isNotBlank(pictureContent.getContentId())){
			pictureContent = (PictureContentBean)dozer.map(pictureContentService.getPictureContent(pictureContent.getContentId()),PictureContentBean.class);
		}
		if(pictureContent!=null&&pictureContent.getCategory()!=null&&StringUtils.isNotBlank(pictureContent.getCategory().getCategoryId())){
			pictureContent.setCategory((CategoryBean)dozer.map(categoryService.getCategory(pictureContent.getCategory().getCategoryId()), CategoryBean.class));
		}
		
	}

	/**
	 * 删除<b>Content</b>记录的方法，成员变量<b>key</b>为主键的String数组，以主键方式进行删作
	 * 删除成功后，返回"reload"，然后跳转到content-list.action
	 */
	@Override
	@Action(value="picturecontent-delete",
			results={@Result(name="reload",type="redirectAction",params={"actionName","content-list?content.category.categoryId=${pictureContent.category.categoryId}"})}
			)
	public String delete(){
		pictureContent = (PictureContentBean)dozer.map(pictureContentService.getPictureContent(key[0]), PictureContentBean.class);
		pictureContentService.delete(key);
		return RELOAD;
	}
	
	/**
	 * Content的列表方法，通过成员变量<b>page�?{insClassName}</b>调用service接口，更新page
	 * 执行成功后，将映射到content-list.jsp页面
	 */
	@Override
	@Action(value="picturecontent-list")
	public String list(){
		setSessionValue(JUMP_FLAG, "");
		pictureContentService.list(page,pictureContent);
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.CONTENT_STATUS)!=null){
			dicContentType = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.CONTENT_STATUS);
		}
		return SUCCESS;
	}
	/**
	 * Content的新增与编辑的方法执行成功能
	 * 将映射到content-input.jsp
	 */
	@Action(value="picturecontent-input")
	public String input(){
		Admin admin = (Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN);
		prepareModel();
		//原状态，直接返回的继续保存为该状态
		status = pictureContent.getContentStatus();
		
		operLog.setOperObjectId(pictureContent.getContentId());
		if(pictureContent!=null&&StringUtils.isNotBlank(pictureContent.getContentId())){
			pictureContentService.save(pictureContentService.getPictureContent(pictureContent.getContentId()), (Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN), DictionaryStaticValues.CONTENT_STATUS_LOCK);
			operLogService.addLog(admin.getLoginName(), admin.getRealName(), Module.CONTENT.getValue(),
					OperAct.LOCK.getValue(), pictureContent.getContentId(), IpUtil.getClientIp(getRequest()));
		}else{
			pictureContent.setPublishTime(new Date());
			pictureContent.setAuditTime(new Date());
		}
		if(StringUtils.isNotBlank(cflag)){
			dicAudit = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.AUDIT_TYPE);
			operLogList = operLogService.getLogInfos((OperLogBean)dozer.map(operLog,OperLogBean.class));
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_TOP)!=null){
			dicIsTop = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_TOP);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_COMMENT)!=null){
			dicIsComment = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.IS_COMMENT);
		}
		if(dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.CONTENT_PUBLISH_TYPE)!=null){
			dicPublishType = dictionaryService.getDictionaryListByTypeCode(DictionaryStaticValues.CONTENT_PUBLISH_TYPE);
		}
		if(contenttpllist.size()==0){
			if(pictureContent.getCategory()!=null){
				String[] CatContentTplSet1=null;
				if(StringUtils.isNotBlank(pictureContent.getCategory().getCatDefaultContentTpl())){
					if(pictureContent.getCategory().getCatDefaultContentTpl().contains("-")){
						CatContentTplSet1=pictureContent.getCategory().getCatDefaultContentTpl().split("-");
						for (String ss : CatContentTplSet1) {
							contenttpllist.add(ss);
						}
					}else{
						contenttpllist.add(pictureContent.getCategory().getCatDefaultContentTpl());
					}		
				}
				checkRepeatList=contenttpllist;					
				String[] CatContentTplSet2=null;
				if(StringUtils.isNotBlank(pictureContent.getCategory().getCatContentTplSet())){
					if(pictureContent.getCategory().getCatContentTplSet().contains("-")){
						CatContentTplSet2=pictureContent.getCategory().getCatContentTplSet().split("-");
						for (String ss : CatContentTplSet2) {
							boolean conFlag=false;
							for(int i=0;i<checkRepeatList.size();i++){	
								if(checkRepeatList.get(i).equals(ss)){
									conFlag=true;
								}
							}
							if(conFlag==false){
								contenttpllist.add(ss);
							}
						
						}
					}else{						
						String catconset=pictureContent.getCategory().getCatContentTplSet();
						for(int i=0;i<checkRepeatList.size();i++){
							if(checkRepeatList.get(i).equals(catconset)){
								break;
							}
							else{
								contenttpllist.add(catconset);
							}
						}
					}	
				}
			}	
		}
		
		if(toptpllist.size()==0){
			 if(topic!=null){
				topic=topicService.getTopic(topic.getTopicId());
				String[] CatContentTplSet3=null;
				if(StringUtils.isNotBlank(topic.getTopicDefaultContentTpl())){
					if(topic.getTopicDefaultContentTpl().contains("-")){
						CatContentTplSet3=topic.getTopicDefaultContentTpl().split("-");
						for (String ss : CatContentTplSet3) {
							toptpllist.add(ss);
						}
					}else{
						toptpllist.add(topic.getTopicDefaultContentTpl());
					}		
				}
				checkRepeatList=toptpllist;
				String[] CatContentTplSet4=null;
				if(StringUtils.isNotBlank(topic.getTopicContentTplSet())){
					if(topic.getTopicContentTplSet().contains("-")){
						CatContentTplSet4=topic.getTopicContentTplSet().split("-");
						for (String ss : CatContentTplSet4) {
							boolean topicFlag=false;
							for(int i=0;i<checkRepeatList.size();i++){
								if(checkRepeatList.get(i).equals(ss)){
									topicFlag=true;
								}									
							}
							if(topicFlag==false){
								toptpllist.add(ss);
							}
						}
					}else{
						String conset=topic.getTopicContentTplSet();
						for(int i=0;i<checkRepeatList.size();i++){
							if(checkRepeatList.get(i).equals(conset)){
								break;
							}else{
								toptpllist.add(conset);
							}
						}
					}	
				}
			}
		}	
		return INPUT;
	}
	
	/**
	 * save or update Content的方法，将成员property content转成Content实例，执行保存；
	 * 执行成功后，返回"reload"，然后跳转到content-list.action
	 */
	@Override
	@Action(value="picturecontent-save",
			results={
			@Result(name="site",location="/content/content-site.action",type="redirect"),
			@Result(name="reload",type="redirectAction",params={"actionName","content-list?content.category.categoryId=${pictureContent.category.categoryId}"}),
			 @Result(name="topic",type="redirectAction",params={"actionName","content-list?topic.topicId=${topic.topicId}&tflag=1"})}
		)
	public String save(){
		PictureContent obj = (PictureContent) dozer.map(pictureContent, PictureContent.class);
		obj.setSiteId(getCurrentSiteId());
		if(!StringUtils.isNotBlank(obj.getContentId())){
			obj.setContentId(null);
			obj.setIsLocked(new Boolean(false));
			operLog.setOperAct(OperAct.ADD.getValue());
			if(topic != null&&StringUtils.isNotBlank(topic.getTopicId())){
				Topic t = topicService.getTopic(topic.getTopicId());
				if(t.getIsAudit()){
					obj.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_NEW);					
				}else {
					obj.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_SUCCESS);		
				}
			}else if(pictureContent.getCategory() != null&&StringUtils.isNotBlank(pictureContent.getCategory().getCategoryId())){
				Category  c = categoryService.getCategory(pictureContent.getCategory().getCategoryId());
				if(c.getIsAudit()){
					obj.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_NEW);					
				}else {
					obj.setContentStatus(DictionaryStaticValues.CONTENT_STATUS_SUCCESS);		
				}
			}
		}else{
			if("1".equals(cflag)){
				operLog.setOperAct(OperAct.ADUIT.getValue());
			}else{
				operLog.setOperAct(OperAct.EDIT.getValue());
				obj.setPublishSug(null);
			}
		}
		Admin admin = (Admin)getSessionValue(ConstantWebApp.CURRENT_ADMIN);
		if(topic != null){
			obj.setTopic(new Topic(topic.getTopicId()));
		}
		
		//1 list+index+content
				//2 content
		if(StringUtils.isNotBlank(pictureContent.getAndPub())){
			pictureContentService.save(obj,admin,DictionaryStaticValues.CONTENT_STATUS_PUBLISH);
			contentAttachService.updateContentAttach(contentAttach.getAttachId(), contentAttach.getAttachMemo(),obj);
			operLogService.addLog(admin.getLoginName(), admin.getRealName(), Module.CONTENT.getValue(), 
					OperAct.ADD_PUBLISH.getValue(), obj.getContentId(), IpUtil.getClientIp(getRequest()));
			publishContents(obj,!"1".equals(pictureContent.getAndPub()));
		}
		
		else{
			pictureContentService.save(obj,admin,cflag);
			contentAttachService.updateContentAttach(contentAttach.getAttachId(), contentAttach.getAttachMemo(),obj);
			operLogService.addLog(admin.getLoginName(), admin.getRealName(), Module.CONTENT.getValue(),
					OperAct.ADD_PUBLISH.getValue(), obj.getContentId(), IpUtil.getClientIp(getRequest()));
		}
		
		if(ContentStatic.cab!=null){
			ContentStatic.cab.remove(obj.getContentId());
		}
		if(StringUtils.isBlank((String)getSessionValue(JUMP_FLAG))){
			if(topic != null && StringUtils.isNotBlank(topic.getTopicId())){
				return TOPIC;
			}else{
				return RELOAD;
			}
		}else{
			return "site";
		}
	}
	@Action(value="picturecontent-listpic")
	public String getPic(){
		String ids = "";
		String memos = "";
		String urls = "";
		String sizes = "";
		String names = "";
		for(String id:key[0].split(",")){
			ContentAttach ca = contentAttachService.getContentAttach(id);
			ids +=ca.getAttachId()+"@";
			memos += ca.getAttachMemo()+"@";
			urls +=ca.getAttachUrl()+"@";
			sizes +=ca.getAttachSize()+"@";
			names +=ca.getAttachName()+"@";
		}
		String info = "{ids:'"+ids+"',memos:'"+memos+"',urls:'"+urls+"',sizes:'"+sizes+"',names:'"+names+"'}";
		return renderText(info);
	}
	
	@Action(value="picturecontent-savememo")
	public void savePicMemo() throws Exception{
		if(contentAttach!=null&&StringUtils.isNotBlank(contentAttach.getAttachId())&&StringUtils.isNotBlank(contentAttach.getAttachMemo())){
			String[] ids = contentAttach.getAttachId().split("@");
			String[] memos = new String(contentAttach.getAttachMemo().getBytes("iso-8859-1"),"utf-8").split("@");
			for(int i = 0 ; i < ids.length ; i ++){
				ContentAttach ca = contentAttachService.getContentAttach(ids[i]);
				ca.setAttachMemo(memos[i]);
				contentAttachService.save(ca);
			}
		}
	}
	
	private synchronized void publishContents(Content obj,boolean onlyContent){
	}
	
	private List<String> getCategoryList(Category obj){
		List<String> list = new ArrayList<String>();
		if(obj.getCategory()!=null){
			Category c = categoryService.getCategory(obj.getCategory().getCategoryId());
			list.addAll(getCategoryList(c));
		}
		list.add(obj.getCategoryId());
		return list;
	}
	
	/**
	 * 获取数据字典KEY值对应的NAME
	 * 
	 * @param key
	 * @param type
	 *            数据字典类型
	 * @return
	 */
	public String getName(String key,String code) {
		return dictionaryService.getDictionaryByDictionaryKey(key,code).getDictionaryValue();
	}

	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

	public List<String> getContenttpllist() {
		return contenttpllist;
	}

	public void setContenttpllist(List<String> contenttpllist) {
		this.contenttpllist = contenttpllist;
	}

	public List<String> getToptpllist() {
		return toptpllist;
	}

	public void setToptpllist(List<String> toptpllist) {
		this.toptpllist = toptpllist;
	}

	public List<String> getCheckRepeatList() {
		return checkRepeatList;
	}

	public void setCheckRepeatList(List<String> checkRepeatList) {
		this.checkRepeatList = checkRepeatList;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
	
}